// localStorage 操作类
var lsName = 'localStorage', ls = undefined;

var Store = function(){
  this.version = '0.0.1';

  ls = this.support();
  if(ls === false){
    console.warn('localStorage is not supported！');
    return;
  }

  if(!(this instanceof Store)){
       return new Store();
   }
};

Store.prototype={
  constructor: Store,
  support:function () {
    try {
      return (lsName in window && window[lsName])
    }catch(e){
      return false
    }
  },
  parseJSON: function(v) {
    if (typeof v != 'string') { return undefined }
    try { return JSON.parse(v) }
    catch (e) { return v || undefined }
  },
  set: function(key, val, seconds) {
    if (val === undefined) { return store.remove(key) }

    ls.setItem(key, JSON.stringify(val))
    if(/\d+/.test(seconds)){
      if(seconds<=0) return
      ls.setItem(key+'_t', JSON.stringify({start:new Date().getTime(), expires:seconds }))
    }
    //清空所有过期的数据
    this.refreshData()

    return val
  },
  refreshData: function () {
    // 检查所有存储的数据是否过期，过期则清除
    var nowT = new Date().getTime()
    var self = this, oldT, timespan

    self.keys().filter(function(v, i){
      return /_t$/.test(v)
    }).forEach(function(v, i){
        oldT = self.get(v)
        var timespan = nowT - oldT.start
        if(timespan > parseFloat(oldT.expires)*1000){
          self.remove(v)
          self.remove(v.split('_')[0])
        }
    })
  },
  get: function (key, callback) {
    if(!ls.hasOwnProperty(key)) return ''

    var val = store.parseJSON(ls.getItem(key))
    // 不带时间的数据直接返回
    if(!ls.hasOwnProperty(key+'_t')) return val

    // 带时间的数据，判断是否超时
    var oldT = JSON.parse(ls.getItem(key+'_t'))
    var timespan = new Date().getTime() - oldT.start

    if(timespan > parseInt(oldT.expires)*1000){
      store.remove(key)
      store.remove(key+'_t')
      return ''
    }else{
      return val
    }
  },
  has: function (key) {
    return ls.hasOwnProperty(key)
  },
  remove: function (key) {
    ls.removeItem(key)
  },
  clear:function () {
    ls.clear()
  },
  getAll: function () {
    var ret = {}
    this.forEach(function(i, v){ ret[i] = v })
    return ret
  },
  keys: function () {
    if(Object.keys) return Object.keys(ls)

    var keys = [], key=''
    for(key in ls){
      if(ls.hasOwnProperty(key)) keys.push(key)
    }
    return keys
  },
  forEach: function (callback) {
    for (var i=0; i<ls.length; i++) {
      var key = ls.key(i)
      callback(key, store.get(key))
    }
  },
}

export default Store()
